package com.engine.core.gen;

import com.engine.core.util.PackageUtils;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.AbstractVariadicFunction;
import com.googlecode.aviator.runtime.type.AviatorFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import java.util.Set;

@Configuration
public class AviatorConfig  implements ApplicationContextAware {

    @Autowired
    private Global global ;
    private static Logger logger= LoggerFactory.getLogger(AviatorConfig.class);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        String packages = "com.engine.aviator.funs";
        packages=global.getAviator().getOrDefault("config-path",packages);
        Set<String> allPackages = PackageUtils.findPackageClass(packages);
        allPackages.forEach(s->{
            try {
                Class<?> aClass = Class.forName(s);
                if(AbstractFunction.class.isAssignableFrom(aClass)
                     || AbstractVariadicFunction.class.isAssignableFrom(aClass)){
                    AviatorFunction aviatorFunction = (AviatorFunction) aClass.newInstance();
                    AviatorEvaluator.addFunction(aviatorFunction);
                }
            } catch (Exception e) {
                logger.error("AviatorConfig setting",e);
            }
        });

   }
}
